package com.lsfb.signln.My;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.lsfb.signln.Login.Face.FirstFaceActivity;
import com.lsfb.signln.Login.LoginActivity;
import com.lsfb.signln.My.BoundPhone.BoundPhoneActivity;
import com.lsfb.signln.My.ChangePwd.ChangePwdActivity;
import com.lsfb.signln.My.Feedback.FeedbackActivity;
import com.lsfb.signln.R;
import com.lsfb.signln.Utils.DataCleanManager;
import com.lsfb.signln.Utils.LittleUtils;
import com.lsfb.signln.Utils.MyDialog;
import com.lsfb.signln.Utils.URLString;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.LsfbFragment;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInjectUtils;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.net.HttpClient;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.T;
import com.zgscwjm.lsfbbasetemplate.view.Camera.LsfbCamera;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/1/23 0023.
 */

public class MyFragment extends LsfbFragment {

    private View view;

    /**
     * activity对象
     */
    private Activity mactivity;

    /**
     * 头像
     */
    @ViewInject(R.id.fg_img_head)
    private SimpleDraweeView fg_img_head;

    private String img_uri;

    /**
     * 文字头像
     */
    @ViewInject(R.id.fg_text_head)
    private TextView fg_text_head;

    /**
     * 名称
     */
    @ViewInject(R.id.fg_my_text_name)
    private TextView text_name;

    /**
     * 职位
     */
    @ViewInject(R.id.fg_my_text_position)
    private TextView text_position;

    /**
     * 手机号
     */
    @ViewInject(R.id.fg_my_text_phone)
    private TextView text_phone;

    /**
     * 缓存数
     */
    @ViewInject(R.id.fg_clear_text_num)
    private TextView text_num;

    /**
     * 消息提醒图
     */
    @ViewInject(R.id.fg_remind_img)
    private ImageView remind_img;

    /**
     * 消息提醒是否开启，默认开启
     */
    private boolean remind = true;

    private MyDialog.Builder builder;
    private MyDialog mDialog;

    /**
     * 封装好的照相机
     */
    private LsfbCamera camera;

    /**
     * uir存储
     */
    private Uri muri;

    /**
     * 头像上传回调所用常量
     */
    private static final int REQUEST_CODE_WRITE_SETTINGS = 2;

    private static final int RESULT_OK = -1;

    /**
     * 用于更新主线程UI
     */
    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case 1000:
                    T.showShort(getActivity(), "清理缓存完成");
                    text_num.setText("0KB");
                    break;
                case 2000:
                    fg_img_head.setVisibility(View.VISIBLE);
                    fg_text_head.setVisibility(View.GONE);
                    fg_img_head.setImageURI(Uri.parse(URLString.IMAGES + img_uri));
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_my, null);
            ViewInjectUtils.inject(this, view);
        }

        try {
            text_num.setText(DataCleanManager.getTotalCacheSize(mactivity.getApplicationContext()));
        } catch (Exception e) {
            e.printStackTrace();
            LsfbLog.e("获取缓存大小出错" + e.getMessage());
            text_num.setText("0KB");
        }

        builder = new MyDialog.Builder(mactivity);

        camera = new LsfbCamera() {
            @Override
            public void resultUri(Uri uri) {
                muri = uri;
            }
        };
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mactivity = activity;
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.fg_my_head, R.id.fg_change_pwd, R.id.fg_change_face, R.id.fg_change_phone, R.id.fg_feedback, R.id.fg_clear, R.id.fg_remind, R.id.fg_exit})
    public void onClick(View view) {
        switch (view.getId()) {
            //头像
            case R.id.fg_my_head:
                camera.show(mactivity, mactivity);
                break;
            //修改密码
            case R.id.fg_change_pwd:
                startActivity(new Intent(mactivity, ChangePwdActivity.class));
                break;
            //人脸信息修改
            case R.id.fg_change_face:
                startActivity(new Intent(mactivity, FirstFaceActivity.class).putExtra("type", "2"));
                break;
            //手机号
            case R.id.fg_change_phone:
                startActivity(new Intent(mactivity, BoundPhoneActivity.class));
                break;
            //意见反馈
            case R.id.fg_feedback:
                startActivity(new Intent(mactivity, FeedbackActivity.class));
                break;
            //清除缓存
            case R.id.fg_clear:
                DataCleanManager.cleanApplicationData(mactivity.getApplicationContext(), "");
                handler.sendEmptyMessageDelayed(1000, 2000);
                T.showShort(mactivity, "缓存清理中...");

                break;
            //消息提醒
            case R.id.fg_remind:
                if (remind) {
                    remind_img.setImageResource(R.mipmap.img_off);
                    remind = false;
                } else {
                    remind_img.setImageResource(R.mipmap.img_on);
                    remind = true;
                }
                break;
            //退出登录
            case R.id.fg_exit:
                exit(null, null, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDialog.dismiss();

                        LittleUtils.exit(mactivity);
//                        SPUtils.remove(mactivity, "et_username");
//                        SPUtils.remove(mactivity, "et_password");
                        startActivity(new Intent(mactivity, LoginActivity.class));
                        mactivity.finish();
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mDialog.dismiss();
                        //取消
                    }
                });
                break;
        }
    }

    public void exit(String confirmText, String cancelText, View.OnClickListener conFirmListener, View.OnClickListener cancelListener) {
        mDialog = builder.setPositiveButton(confirmText, conFirmListener)
                .setNegativeButton(cancelText, cancelListener)
                .setContext("确定退出程序")
                .createTwoButtonDialog();
        mDialog.show();
    }

    @Override
    protected void Resume() {

    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    @Override
    public void initData() {
        getData();
    }

    /**
     * 获取个人信息
     */
    private void getData() {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        new BaseInternet().getData_Get(URLString.INFO, hashMap, MyDetailsBean.class, new MyDetailsEvent<MyDetailsBean>(), true, false);
    }

    @EventAnnotation
    public void MyDetailsEvent(MyDetailsEvent<MyDetailsBean> event) {
        switch (event.getCode()) {
            case 200:
                if (event.getData().getHeadImg().isEmpty()) {
                    fg_img_head.setVisibility(View.GONE);
                    fg_text_head.setVisibility(View.VISIBLE);
                    fg_text_head.setText(event.getData().getUserName().substring(event.getData().getUserName().length() - 2, event.getData().getUserName().length()));
                } else {
                    fg_img_head.setVisibility(View.VISIBLE);
                    fg_text_head.setVisibility(View.GONE);
                    fg_img_head.setImageURI(Uri.parse(URLString.IMAGES + event.getData().getHeadImg()));
                }
                text_name.setText(event.getData().getUserName());
                text_position.setText(event.getData().getDepartName() + "    " + event.getData().getJobsName());
                text_phone.setText(event.getData().getPhone());
                break;
            case 1006:
                T.showShort(mactivity, "您的账号已在其它设备登录，请重登录");
                LittleUtils.exit(mactivity);
                startActivity(new Intent(mactivity, LoginActivity.class));
                break;
            default:
                T.showShort(getActivity(), event.getMsg());
                break;
        }
    }

    /**
     * 头像选择回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        LsfbLog.e("requestCode" + requestCode);
        LsfbLog.e("resultCode" + resultCode);

        if (requestCode == REQUEST_CODE_WRITE_SETTINGS) {
            if (Settings.System.canWrite(mactivity)) {
                LsfbLog.e("onActivityResult write settings granted");
            } else {
                LsfbLog.e("请求失败");
            }
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case LsfbCamera.REQUESTCODE:
                    LsfbLog.e(muri.toString());
                    camera.crop(muri, 300);
                    break;
                case LsfbCamera.SYSTEMPHOTOS:
                    LsfbLog.e(data.getData().toString());
                    String url = "file://" + LsfbCamera.getPath(mactivity, data.getData());
                    LsfbLog.e("22222222222222" + url);
                    muri = Uri.parse(url);
                    camera.crop(muri, 300);
                    break;
                case LsfbCamera.CROPIMG:
                    LsfbLog.e("---------------------------------------------:" + muri.getPath());
//                    File file = new File(muri.getPath());

                    List<File> list = new ArrayList<>();
                    list.add(new File(muri.getPath()));

                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("img", muri.getPath());
                    // TODO: 2017/4/26 0026 token------
                    new HttpClient().postFile(URLString.UPLOAD, hashMap, list, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                            LsfbLog.e("上传失败" + e.getMessage());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            LsfbLog.e("上传success");
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(response.body().string());
                                LsfbLog.e("上传结果" + jsonObject.toString());
                                if (jsonObject.getInt("code") == 200) {
                                    LsfbLog.e("得到回调");
                                    String img = jsonObject.getString("data");
                                    img_uri = img;
                                    updateHeadimg(img);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                    break;
            }
        }
    }

    /**
     * 更新用户头像
     */
    public void updateHeadimg(String imgPath) {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("imgPath", imgPath);
        new BaseInternet().getData(URLString.UPDATEHEADIMG, hashMap, String.class, new UpdateHeadimgEvent(), true);
    }

    @EventAnnotation
    public void UpdateHeadimgEvent(UpdateHeadimgEvent event) {
        switch (event.getCode()) {
            case 200:
                handler.sendEmptyMessage(2000);
                break;
            case 1006:
                T.showShort(mactivity, "您的账号已在其它设备登录，请重登录");
                LittleUtils.exit(mactivity);
                startActivity(new Intent(mactivity, LoginActivity.class));
                break;
            default:
                T.showShort(getActivity(), event.getMsg());
                break;
        }
    }

}
